<!-- src/views/BenchmarkReportList.vue -->
<template>
  <div class="benchmark-report-list">
    <!-- 批量操作工具栏 -->
    <div style="margin-bottom: 10px" v-if="multipleSelection.length > 0">
      <el-button size="small" type="danger" @click="handleBatchDelete">
        批量删除 ({{ multipleSelection.length }})
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="benchmarkData"
      @selection-change="handleSelectionChange"
      highlight-current-row
      ref="tableRef"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="60" />

      <!-- 用例名称 -->
      <el-table-column label="用例名称" prop="case_name" min-width="180">
        <template #default="{ row }">
          <span class="case-name">{{ row.test_case_name }}</span>
        </template>
      </el-table-column>

      <!-- 并发数 -->
      <el-table-column label="并发数" prop="concurrent_users" width="100">
        <template #default="{ row }">
          {{ row.concurrent_users }}
        </template>
      </el-table-column>

      <!-- 总请求数 -->
      <el-table-column label="总请求数" prop="total_requests" width="110">
        <template #default="{ row }">
          {{ row.total_requests }}
        </template>
      </el-table-column>

      <!-- 成功请求数 -->
      <el-table-column label="成功数" prop="success_count" width="100">
        <template #default="{ row }">
          <el-tag type="success">{{ row.successful_requests }}</el-tag>
        </template>
      </el-table-column>

      <!-- 失败请求数 -->
      <el-table-column label="失败数" prop="failure_count" width="100">
        <template #default="{ row }">
          <el-tag type="danger">{{ row.failed_requests }}</el-tag>
        </template>
      </el-table-column>

      <!-- RPS -->
      <el-table-column label="RPS" prop="rps" width="100">
        <template #default="{ row }">
          {{ row.rps?.toFixed(2) }}
        </template>
      </el-table-column>

      <!-- 平均响应时间 -->
      <el-table-column label="平均响应(ms)" prop="avg_response_time_ms" width="130">
        <template #default="{ row }">
          {{ Math.round(row.avg_response_time_ms) }}
        </template>
      </el-table-column>

      <!-- 95% 响应时间 -->
      <el-table-column label="P95 响应(ms)" prop="p95_response_time_ms" width="130">
        <template #default="{ row }">
          {{ Math.round(row.p95_response_time_ms) }}
        </template>
      </el-table-column>

      <!-- 吞吐量 -->
      <el-table-column label="吞吐量" prop="throughput_kbps" width="100">
        <template #default="{ row }"> {{ formatBytes(row.throughput_kbps * 1024) }}/s </template>
      </el-table-column>

      <!-- 执行时间 -->
      <el-table-column label="执行时间" prop="timestamp" min-width="160">
        <template #default="{ row }">
          {{ formatDate(row.executed_at) }}
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-button size="small" type="primary" text @click.stop="handleRowClick(row)">
            查看详情
          </el-button>
          <el-button size="small" type="danger" text @click.stop="handleDelete(row.report_id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/services/api'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useReportStore } from '@/stores/reportStore'

const router = useRouter()
const multipleSelection = ref([])
const tableRef = ref()
const reportStore = useReportStore()

// ✅ 使用 store 中的 benchmarkData
const benchmarkData = computed(() => {
  const data = reportStore.benchmarkData
  return Array.isArray(data) ? data : []
})

// 获取压测报告列表
async function fetchData() {
  try {
    const res = await api.get('/benchmark-reports/') // 你的压测报告接口

    // ✅ 转为真数组（防伪数组）
    const reports = Array.from(res.data || [])
    console.log('res.data', res.data)

    // 存入 store
    reportStore.benchmarkData = reports
  } catch (error) {
    console.error('获取压测报告失败:', error)
    ElMessage.error('加载压测数据失败')
    reportStore.benchmarkData = []
  }
}

// 多选
function handleSelectionChange(selection) {
  multipleSelection.value = selection
}

// 单条删除
async function handleDelete(reportId) {
  try {
    await ElMessageBox.confirm('确定要删除这条压测报告吗？', '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await api.delete(`/benchmark-reports/${reportId}/`)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('删除失败')
  }
}

// 批量删除
async function handleBatchDelete() {
  const ids = multipleSelection.value.map((r) => r.report_id)
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 条压测报告吗？`, '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    for (const id of ids) {
      await api.delete(`/benchmark-reports/${id}/`)
    }

    ElMessage.success(`成功删除 ${ids.length} 条报告`)
    fetchData()
    tableRef.value.clearSelection()
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('批量删除失败')
  }
}

// 查看详情
function handleRowClick(row) {
  router.push(`/reports/benchmark-detail/${row.report_id}`)
  sessionStorage.setItem('currentBenchmarkReport', JSON.stringify(row))
}

// 工具函数（复用）
const formatBytes = (bytes) => {
  if (bytes < 1024) return `${bytes}B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`
  return `${(bytes / 1024 / 1024).toFixed(1)}MB`
}

const formatDate = (iso) => new Date(iso).toLocaleString('zh-CN')

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.benchmark-report-list {
  padding: 20px;
}

.case-name {
  font-weight: 500;
}
</style>
